import os
import shutil
import pandas as pd
# from . import utils

ROOT_PATH = "F:\\Download\\mav\\hanime\\"
#ROOT_PATH = "D:\\Download\\mav\\"

# 去除前后空白字串
def trim(s):
    if(s==None or s == ''):
        return ''
    # 左侧空格
    while(s[:1] == ' ' or s[:1] == '\t' or s[:1] == '\n'):
        s = s[1:]
    # 右侧空格
    while(s[-1:] == ' ' or s[-1:] == '\t' or s[-1:] == '\n'):
        s = s[:-1]
    return s

def check_filename(name):
    name = (str(name) or "").replace("?", "")
    name = name.replace("|", "")
    name = name.replace("\\", "")
    name = name.replace("/", "")
    name = name.replace(".", "")
    name = name.replace(":", "")
    name = name.replace(">", "")
    name = name.replace("<", "")
    name = name.replace('"', "")
    name = name.replace('*', "")
    return name

def RebuildFolder(topic):
    # 读取CSV文件
    #topic = utils.trim(topic)
    file_name = topic
    if file_name == "3D":
        file_name = "d3"
    csv_file = f'..\\{file_name}.csv'
    #print("csv_file=", csv_file)
    df = pd.read_csv(csv_file)
    df = df.drop_duplicates()
    if topic == "comics":
        df = df.loc[:, ['id', 'author', 'title']] # , 'download_list'
    else:
        df = df.loc[:, ['id', 'author', 'group', 'title']] # , 'download_list'
    # 显示前几行数据
    #print(df.head())
    for row in df.itertuples():
        id = row.id
        author = row.author
        if type(author) == list:
            author = author[0]
        author = trim(str(author).split(",", maxsplit=1)[0])
        author = trim(str(author).split("|", maxsplit=1)[0])
        author = check_filename(author)
        title = check_filename(row.title)
        if topic == "comics":
            group = ""
            folder = id
            #download_list = []
        else:
            group = row.group
            folder = group
            #download_list = row.download_list
        folder = check_filename(folder)
        #print(f"Index: {row.Index}, id: {id}, author: {author}, group: {group}, title: {title}")
        old_path = os.path.join(ROOT_PATH, topic, folder)
        new_topic = topic
        if topic != "comics":
            new_topic = topic + "2"
        new_path = os.path.join(ROOT_PATH, new_topic, author, folder)
        print(f"Index: {row.Index}, old_path: {old_path}, new_path: {new_path}")
        if os.path.exists(old_path):
            print(f"MOVE Index: {row.Index}, {old_path} => {new_path}")
            shutil.move(old_path, new_path)
            


#Main Run Thread
if __name__=='__main__':
    print("RebuildFolder :")
    #topic = "3D"
    topic = "comics"
    RebuildFolder(topic)